package com.guli.gulimall.gulimallproduct.controller;

import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import com.guli.common.utils.ImageBeans;
import com.guli.common.valid.AddGroup;
import com.guli.gulimall.gulimallproduct.dao.BrandDao;
import com.guli.gulimall.gulimallproduct.feign.COSForignService;
import feign.Response;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.bind.DefaultValue;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.guli.gulimall.gulimallproduct.entity.BrandEntity;
import com.guli.gulimall.gulimallproduct.service.BrandService;
import com.guli.common.utils.PageUtils;
import com.guli.common.utils.R;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

/**
 * 品牌
 *
 * @author zouzhi
 * @email 1245268075@qq.com
 * @date 2022-04-03 10:19:09
 */
@RestController
@RequestMapping("gulimallproduct/brand")
@Api(value = "BrandController接口", tags = "品牌接口")
public class BrandController {
    @Autowired
    private BrandService brandService;
    @Autowired
    private BrandDao brandDao;
//    @Autowired
//    private COSClient cosClient;

//    @Value("${cos.aipid}")
//    private String apiid;

    @Resource
    private COSForignService cosForignService;
    private static final ReentrantReadWriteLock reentrantReadWriteLoc;

    static {
        reentrantReadWriteLoc = new ReentrantReadWriteLock();
    }

    /**
     * 列表
     */
    @GetMapping("/list")
    @ApiOperation("按页查询品牌")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = brandService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @GetMapping("/info/{brandId}")
    @ApiOperation("根据品牌id查询品牌信息")
    public R info(@PathVariable("brandId") Long brandId) {
        BrandEntity brand = brandService.getById(brandId);

        return R.ok().put("brand", brand);
    }

    /**
     * 保存
     */
    @PostMapping("/save")
    @ApiOperation("保存新增的品牌")
    public R save(@RequestBody BrandEntity brand) {
        reentrantReadWriteLoc.writeLock().lock();
        boolean b = false;
        try {
            b = brandService.save(brand);
        } catch (Exception e) {
            return R.error().put("data", "保存失败，请重试");
        } finally {
            reentrantReadWriteLoc.writeLock().unlock();
        }
        return b ? R.ok().put("data", "保存成功") : R.error().put("data", "保存失败，请重试");
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    @ApiOperation("修改品牌信息")
    public R update(@RequestBody BrandEntity brand) {
        reentrantReadWriteLoc.writeLock().lock();
        boolean b;
        try {
            b = brandService.updateDtails(brand);
        } catch (Exception e) {
            return R.error().put("data", "更新失败，请重试");
        } finally {
            reentrantReadWriteLoc.writeLock().unlock();
        }
        return b ? R.ok().put("data", "更新成功") : R.error().put("data", "更新失败，请重试");
    }

    /**
     * 修改
     */
    @PostMapping("/update/status")
    @ApiOperation("修改品牌是否可见的状态")
    public R updateStatus(@RequestBody BrandEntity brand) {
        reentrantReadWriteLoc.writeLock().lock();
        boolean b;
        try {
            b = brandService.updateById(brand);
        } catch (Exception e) {
            return R.error().put("data", "更新失败，请重试");
        } finally {
            reentrantReadWriteLoc.writeLock().unlock();
        }
        return b ? R.ok().put("data", "更新成功") : R.error().put("data", "更新失败，请重试");
    }

    /**
     * 删除
     */
    @PostMapping("/delete")
    @ApiOperation("删除品牌")
    public R delete(@Valid  @RequestBody Long[] brandIds) {

        reentrantReadWriteLoc.writeLock().lock();
        boolean b;
        try {
            b = brandService.removeByIds(Arrays.asList(brandIds));
        } catch (Exception e) {

            return R.error().put("data", "删除失败，请重试");
        } finally {
            reentrantReadWriteLoc.writeLock().unlock();
        }
        return b ? R.ok().put("data", "删除成功") : R.error().put("data", "删除失败，请重试");
    }


    /**
     * 获取最大的品牌
     */
    @GetMapping("/maxid")
    @ApiOperation("获取最大的品牌id")
    public R getMAXID() {
        Integer brandId = this.brandDao.getMaxID();
        brandId = (brandId == null ? 1 : brandId + 1);
        return R.ok().put("data", brandId);
    }

    @PostMapping("/qclolud/createBucket/{name}")
    @ApiOperation("创建桶")
    public R createBucket(@PathVariable String name) throws IOException {
        return cosForignService.createBucket(name);
    }

    @PostMapping("/qclolud/listBucket")
    @ApiOperation("查询桶")
    public R listBucket() throws IOException {
        return cosForignService.listBucket();
    }

    @PostMapping("/qclolud/delBucket/{bucketName}")
    @ApiOperation("删除桶")
    public R delBucket(@Valid @PathVariable String bucketName) throws IOException {
        return cosForignService.delBucket(bucketName);
    }
    @ApiOperation(value = "上传对象",notes = "这种方式采用服务端上传，浪费服务端资源，不建议采用,建议采用服务端传授临时签名，然后，前端通过临时签名直接从浏览器向COS云端直传文件")
    @PostMapping("/qclolud/upload/{brand_id}/{bucketName}/{localPath}")
    public R uploadObject(@Valid @RequestParam("file") MultipartFile file, @PathVariable String brand_id,
                          @PathVariable String bucketName, @PathVariable String localPath) throws IOException {
        return cosForignService.uploadObject(file, brand_id, bucketName, localPath);
    }

    @GetMapping(value = "/qclolud/download", produces = {"image/jpeg", "image/jpg", "image/png"})
    @ApiOperation(value = "下载图像",notes = "这种方式采用浏览器向前端发送请求，然后由服务端从COS云端下载图像再将资源响应给浏览器，耗费了服务端的性能" +
            "为了性能，我们采取后面的浏览器申请预签名，然后再通过预签名下载图像")
    public void getKaptchaImage(HttpServletRequest request, HttpServletResponse response, @RequestParam("path") String path) throws Exception {
        ImageBeans  r = cosForignService.getKaptchaImage(path);
        byte[] bytes = r.getByteArrayOutputStream();
        String[] temp = path.split("\\@");
        if (temp.length == 2) {
            String key = temp[1];
            String fa = key.split("\\.")[1];
            ServletOutputStream responseOutputStream = response.getOutputStream();
            response.setHeader("Cache-Control", "no-store");
            response.setHeader("Pragma", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setContentType("image/" + fa);
            responseOutputStream.write(bytes);
        }
    }

//    @PostMapping(value = "/qclolud/uploadurl/{bucketName}/{localPath}/{filename}")
//    @ApiOperation(value = "已经废弃")
//    public R generatePresignedUploadUrl(@PathVariable String bucketName, @PathVariable String localPath, @PathVariable String filename){
//        System.out.println(bucketName+"/"+localPath+"/"+filename);
//        return this.cosForignService.generatePresignedUploadUrl(bucketName,localPath,filename);

//    }

    @GetMapping(value = "/qclolud/downloadurl/")
    @ApiOperation(value = "通过预签名下载对象")
    public String generatePresigneddownloadurl(@Validated(AddGroup.class)  @RequestParam("path") String path){
        String[] temp = path.split("\\@");
        String buckeName =temp[0];
        String pathname =temp[1];
        return this.cosForignService.generatePresigneddownloadurl(buckeName,pathname).get("data").toString();
    }
    @PostMapping(value = "/qclolud/uploadurl/{bucketName}/{path}/{filename}")
    @ApiOperation("获取临时秘钥,用于上传对象")
    public R getTempSecret(@Validated(AddGroup.class) @PathVariable String bucketName,@Validated(AddGroup.class)  @PathVariable String path, @Validated(AddGroup.class) @PathVariable String filename, @RequestParam(defaultValue = "ap-chongqing") String region) {

         return this.cosForignService.getTempSecret(bucketName,path,filename,region);
    }

}
